<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 申请退款
 *
 * @author      Eden
 * @datetime    2016/12/1 22:56
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */
class Refundapply_Model extends API_Model
{

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        $send['state'] = false;
        do {

            if (!$this->checkParams($params) || !$this->checkOrder($params)) {
                $send['error'] = $this->getError();
                break;
            }

            // 是否已经申请退款
            if (!$this->checkIfRefund($params)) {
                $send['error'] = '该订单已申请退款';
                break;
            }

            if ($this->doRefund($params)) {
                $send['state'] = true;
                $send['data'] = array(
                    'msg' => '退款申请成功'
                );
            } else {
                $send['error'] = '退款申请失败';
            }
        } while(false);
        $this->output->send($send);
    }

    /**
     * 退款操作
     * @param array $params
     * @return mixed
     */
    private function doRefund($params = array())
    {
        try {
            $db = clone($this->db);
            $db->trans_start();
            $data = array(
                'userId' => $params['userId'],
                'orderId' => $params['orderId'],
                'cause' => value($params, 'cause', ''),
                'created' => dateTime()
            );
            $db->insert('user_order_refund', $data);
            $id = $db->insert_id();

            $dbOrder = clone($this->db);
            $dbOrder->where('id', $params['orderId']);
            $dbOrder->update('user_order', [
                'status' => 'Refund'
            ]);

            $affected = $dbOrder->affected_rows();

            if ($affected && $id) {
                $db->trans_complete();
                return true;
            }
        } catch(PDOException $e) {
            $this->setError('退款发起失败');
        }
        return false;
    }

    /**
     * 是否已经申请退款
     * @param array $params
     * @return bool
     */
    private function checkIfRefund($params = array())
    {
        $db = clone($this->db);
        $q = $db->get_where('user_order_refund', array('orderId' => $params['orderId']));
        return !empty($q->row_array()) ? false : true;
    }

    /**
     * 检查参数
     * @param array $params
     * @return bool
     */
    private function checkParams($params = array())
    {
        if (empty($params['userId']) || empty($params['orderId']) || empty($params['sn'])) {
            $this->setError('参数错误');
            return false;
        }

        if (empty($params['cause'])) {
            $this->setError('请填写退款原因');
            return false;
        }
        return true;
    }

    /**
     * 检查订单是否有效
     * @param array $params
     * @return bool
     */
    private function checkOrder($params = array())
    {
        $db = clone($this->db);
        $q = $db->get_where('user_order', array('id' => $params['orderId']));
        $row = $q->row_array();
        if (empty($row) || $row['userId'] != $params['userId'] || $row['sn'] != $params['sn']) {
            $this->setError('无效订单');
            return false;
        }

        if ($row['payMode'] !== 'online') {
            $this->setError('货到付款,不予处理');
            return false;
        }

        if ($row['status'] == 'Complete') {
            $this->setError('订单已结束, 无法完成退款申请');
            return false;
        }

        if ($row['status'] == 'Unpaid') {
            $this->setError('订单未付款');
            return false;
        }

        return true;
    }
}

